// controller/categories.js
"use strict";
const Controller = require("egg").Controller;
const moment = require("moment");
class CategoryController extends Controller {
  // 创建分类
  async newCategory() {
    const { ctx } = this;
    ctx.logger.info("创建分类参数", ctx.request.body);
    const data = {
      ...ctx.request.body,
      create_time: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    const result = await ctx.service.category.newCategory(data);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "创建失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: "创建成功",
      success: true,
    };
  }
  // 删除分类
  async deleteCategory() {
    const { ctx } = this;
    ctx.logger.info("删除分类参数", ctx.request.body);
    const { id } = ctx.request.body;
    const result = await ctx.service.category.deleteCategory(id);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "删除失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: "删除成功",
      success: true,
    };
  }
  // 更新分类
  async updateCategory() {
    const { ctx } = this;
    ctx.logger.info("更新分类参数", ctx.request.body);
    const data = ctx.request.body;
    data.modified_time = moment().format("YYYY-MM-DD HH:mm:ss")
    const result = await ctx.service.category.updateCategory(data);
    console.log("result", result);
    if (!result || result.changedRows == 0) {
      ctx.body = {
        code: 500,
        message: "更新失败",
        success: false,
      };
      return;
    }
    ctx.body = {
      code: 200,
      message: "更新成功",
      success: true,
    };
  }
  // 分类列表
  async getCategoryList() {
    const { ctx } = this;
    ctx.logger.info("分类列表参数", ctx.request.query);
    const data = ctx.request.query;
    const result = await ctx.service.category.getCategoryList(data);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "查询失败",
        success: false,
      };
      return;
    }
    ctx.body = result;
  }
  // 分类详情
  async getCategoryDetail() {
    const { ctx } = this;
    ctx.logger.info("分类详情参数", ctx.request.query);
    const { id } = ctx.request.query;
    const result = await ctx.service.category.getCategoryDetail(id);
    console.log("result", result);
    if (!result) {
      ctx.body = {
        code: 500,
        message: "查询失败",
        success: false,
      };
      return;
    }
    result.create_time && (result.create_time = moment(result.create_time).format('YYYY-MM-DD HH:mm:ss'))
    result.modified_time && (result.modified_time = moment(result.modified_time).format('YYYY-MM-DD HH:mm:ss'))
    ctx.body = {
      code: 200,
      success: true,
      data: result,
    };
  }
}

module.exports = CategoryController;
